{% extends "base.html" %}

{% block title %}{{ "编辑客户跟进" if followup else "新建客户跟进" }}{% endblock %}

{% block content %}
<div class="w-full px-4 py-6">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-semibold text-gray-800">{{ "编辑客户跟进" if followup else "新建客户跟进" }}</h1>
        <div>
            <a href="{{ url_for('followup.list_followups') }}" class="inline-flex items-center px-4 py-2 bg-gray-500 text-white text-sm font-medium rounded-md hover:bg-gray-600 transition-colors">
                <i class="fas fa-arrow-left mr-2"></i> 返回列表
            </a>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2">
            <!-- 跟进表单 -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h5 class="text-lg font-medium text-gray-900">跟进信息</h5>
                </div>
                <div class="p-6">
                    <form method="POST" id="followup-form">
                        {{ form.hidden_tag() }}
                        
                        <!-- 客户选择 -->
                        <div class="mb-6">
                            <label for="{{ form.customer_id.id }}" class="block text-sm font-medium text-gray-700 mb-2">客户名称 <span class="text-red-500">*</span></label>
                            {{ form.customer_id(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.customer_id.errors else ""), id="customer-select") }}
                            {% if form.customer_id.errors %}
                            <p class="mt-1 text-sm text-red-600">
                                {% for error in form.customer_id.errors %}
                                {{ error }}
                                {% endfor %}
                            </p>
                            {% endif %}
                            <p class="mt-1 text-sm text-gray-500">选择要跟进的客户</p>
                        </div>

                        <!-- 联系人选择 -->
                        <div class="mb-6">
                            <label for="{{ form.contact_ids.id }}" class="block text-sm font-medium text-gray-700 mb-2">联系人</label>
                            <div class="space-y-2 form-check-container">
                                {% for choice in form.contact_ids %}
                                    <div class="flex items-center">
                                        {{ choice(class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded") }}
                                        {{ choice.label(class="ml-2 block text-sm text-gray-700") }}
                                    </div>
                                {% endfor %}
                            </div>
                            {% if form.contact_ids.errors %}
                            <p class="mt-1 text-sm text-red-600">
                                {% for error in form.contact_ids.errors %}
                                {{ error }}
                                {% endfor %}
                            </p>
                            {% endif %}
                            <p class="mt-1 text-sm text-gray-500">选择跟进的联系人（可选）</p>
                        </div>

                        <!-- 项目选择 -->
                        <div class="mb-6">
                            <label for="{{ form.project_id.id }}" class="block text-sm font-medium text-gray-700 mb-2">关联项目</label>
                            {{ form.project_id(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.project_id.errors else ""), id="project-select") }}
                            {% if form.project_id.errors %}
                            <p class="mt-1 text-sm text-red-600">
                                {% for error in form.project_id.errors %}
                                {{ error }}
                                {% endfor %}
                            </p>
                            {% endif %}
                            <p class="mt-1 text-sm text-gray-500">选择关联的项目（可选）</p>
                        </div>

                        <!-- 跟进时间 -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                            <div>
                                <label for="{{ form.followup_time.id }}" class="block text-sm font-medium text-gray-700 mb-2">跟进时间 <span class="text-red-500">*</span></label>
                                {{ form.followup_time(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.followup_time.errors else ""), value=form.followup_time.data.strftime('%Y-%m-%dT%H:%M') if form.followup_time.data else '') }}
                                {% if form.followup_time.errors %}
                                <p class="mt-1 text-sm text-red-600">
                                    {% for error in form.followup_time.errors %}
                                    {{ error }}
                                    {% endfor %}
                                </p>
                                {% endif %}
                            </div>
                            <div>
                                <label for="{{ form.method.id }}" class="block text-sm font-medium text-gray-700 mb-2">跟进方式 <span class="text-red-500">*</span></label>
                                {{ form.method(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.method.errors else "")) }}
                                {% if form.method.errors %}
                                <p class="mt-1 text-sm text-red-600">
                                    {% for error in form.method.errors %}
                                    {{ error }}
                                    {% endfor %}
                                </p>
                                {% endif %}
                            </div>
                        </div>

                        <!-- 跟进内容 -->
                        <div class="mb-6">
                            <label for="{{ form.content.id }}" class="block text-sm font-medium text-gray-700 mb-2">跟进内容 <span class="text-red-500">*</span></label>
                            {{ form.content(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.content.errors else ""), rows="5", placeholder="请输入本次跟进的具体内容...") }}
                            {% if form.content.errors %}
                            <p class="mt-1 text-sm text-red-600">
                                {% for error in form.content.errors %}
                                {{ error }}
                                {% endfor %}
                            </p>
                            {% endif %}
                            <p class="mt-1 text-sm text-gray-500">详细记录跟进的内容和交流情况</p>
                        </div>

                        <!-- 跟进结果 -->
                        <div class="mb-6">
                            <label for="{{ form.result.id }}" class="block text-sm font-medium text-gray-700 mb-2">跟进结果</label>
                            {{ form.result(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.result.errors else ""), rows="4", placeholder="请输入本次跟进的结果...") }}
                            {% if form.result.errors %}
                            <p class="mt-1 text-sm text-red-600">
                                {% for error in form.result.errors %}
                                {{ error }}
                                {% endfor %}
                            </p>
                            {% endif %}
                            <p class="mt-1 text-sm text-gray-500">记录跟进的结果和反馈</p>
                        </div>

                        <!-- 下次跟进时间 -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                            <div>
                                <label for="{{ form.next_followup_time.id }}" class="block text-sm font-medium text-gray-700 mb-2">下次跟进时间</label>
                                {{ form.next_followup_time(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.next_followup_time.errors else ""), value=form.next_followup_time.data.strftime('%Y-%m-%dT%H:%M') if form.next_followup_time.data else '') }}
                                {% if form.next_followup_time.errors %}
                                <p class="mt-1 text-sm text-red-600">
                                    {% for error in form.next_followup_time.errors %}
                                    {{ error }}
                                    {% endfor %}
                                </p>
                                {% endif %}
                                <p class="mt-1 text-sm text-gray-500">设置下次跟进的时间（可选）</p>
                            </div>
                        </div>

                        <!-- 解决方案配合 -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                            <div>
                                <label for="{{ form.solution_support.id }}" class="block text-sm font-medium text-gray-700 mb-2">需要解决方案配合</label>
                                <div class="flex items-center">
                                    {{ form.solution_support(class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded") }}
                                    <label class="ml-2 block text-sm text-gray-700" for="{{ form.solution_support.id }}">
                                        需要解决方案人员配合
                                    </label>
                                </div>
                            </div>
                            <div id="solution-support-user-container" style="display: none;">
                                <label for="{{ form.solution_support_user_id.id }}" class="block text-sm font-medium text-gray-700 mb-2">配合人员</label>
                                {{ form.solution_support_user_id(class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" + (" border-red-500" if form.solution_support_user_id.errors else "")) }}
                                {% if form.solution_support_user_id.errors %}
                                <p class="mt-1 text-sm text-red-600">
                                    {% for error in form.solution_support_user_id.errors %}
                                    {{ error }}
                                    {% endfor %}
                                </p>
                                {% endif %}
                            </div>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="flex justify-end space-x-3">
                            <a href="{{ url_for('followup.list_followups') }}" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                <i class="fas fa-times mr-2"></i> 取消
                            </a>
                            <button type="submit" class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                <i class="fas fa-save mr-2"></i> {{ "更新" if followup else "保存" }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="lg:col-span-1 space-y-6">
            <!-- 客户信息预览 -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden" id="customer-preview" style="display: none;">
                <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                    <h3 class="text-lg font-medium text-gray-900">客户信息</h3>
                </div>
                <div class="p-6">
                    <div class="space-y-4">
                        <div>
                            <p class="text-sm font-medium text-gray-500">客户名称</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-customer-name">-</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-500">行业</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-customer-industry">-</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-500">联系人</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-customer-contacts">-</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-500">联系电话</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-customer-phone">-</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-500">地址</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-customer-address">-</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 联系人信息预览 -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden" id="contact-preview" style="display: none;">
                <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                    <h3 class="text-lg font-medium text-gray-900">联系人信息</h3>
                </div>
                <div class="p-6">
                    <div class="space-y-4">
                        <div>
                            <p class="text-sm font-medium text-gray-500">姓名</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-contact-name">-</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-500">职位</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-contact-position">-</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-500">电话</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-contact-phone">-</p>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-500">邮箱</p>
                            <p class="mt-1 text-sm text-gray-900" id="preview-contact-email">-</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 历史跟进记录 -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden" id="followup-history" style="display: none;">
                <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                    <h3 class="text-lg font-medium text-gray-900">历史跟进记录</h3>
                </div>
                <div class="p-6">
                    <div id="followup-history-list" class="space-y-4">
                        <!-- 历史记录将通过JavaScript动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const customerSelect = document.getElementById('customer-select');
    const projectSelect = document.getElementById('project-select');
    const solutionSupportCheckbox = document.getElementById('{{ form.solution_support.id }}');
    const solutionSupportUserContainer = document.getElementById('solution-support-user-container');
    const customerPreview = document.getElementById('customer-preview');
    const historyPreview = document.getElementById('history-preview');
    
    // 初始化
    updateSolutionSupportVisibility();
    updateCustomerPreview();
    
    // 监听客户选择变化
    customerSelect.addEventListener('change', function() {
        loadCustomerContacts();
        loadCustomerProjects();
        updateCustomerPreview();
        loadFollowupHistory();
    });
    
    // 监听解决方案配合复选框变化
    solutionSupportCheckbox.addEventListener('change', updateSolutionSupportVisibility);
    
    // 更新解决方案配合人员选择框可见性
    function updateSolutionSupportVisibility() {
        if (solutionSupportCheckbox.checked) {
            solutionSupportUserContainer.style.display = 'block';
        } else {
            solutionSupportUserContainer.style.display = 'none';
        }
    }
    
    // 加载客户联系人
    function loadCustomerContacts() {
        const customerId = customerSelect.value;
        if (!customerId) {
            // 清空联系人复选框
            const contactContainer = document.querySelector('.form-check-container');
            if (contactContainer) {
                contactContainer.innerHTML = '<p class="text-gray-500">请先选择客户</p>';
            }
            return;
        }
        
        fetch(`/followup/api/customers/${customerId}/contacts`)
            .then(response => response.json())
            .then(data => {
                const contactContainer = document.querySelector('.form-check-container');
                if (contactContainer) {
                    contactContainer.innerHTML = '';
                    
                    if (data.contacts && data.contacts.length > 0) {
                        data.contacts.forEach(contact => {
                            const checkboxDiv = document.createElement('div');
                            checkboxDiv.className = 'form-check';
                            
                            const checkbox = document.createElement('input');
                            checkbox.type = 'checkbox';
                            checkbox.className = 'h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500';
                            checkbox.id = `contact_${contact.id}`;
                            checkbox.name = 'contact_ids';
                            checkbox.value = contact.id;
                            
                            const label = document.createElement('label');
                            label.className = 'ml-2 block text-sm text-gray-700';
                            label.htmlFor = `contact_${contact.id}`;
                            label.textContent = contact.name;
                            
                            checkboxDiv.appendChild(checkbox);
                            checkboxDiv.appendChild(label);
                            contactContainer.appendChild(checkboxDiv);
                        });
                    } else {
                        contactContainer.innerHTML = '<p class="text-gray-500">该客户暂无联系人</p>';
                    }
                }
            })
            .catch(error => {
                console.error('Error loading contacts:', error);
                const contactContainer = document.querySelector('.form-check-container');
                if (contactContainer) {
                    contactContainer.innerHTML = '<p class="text-red-600">加载联系人失败</p>';
                }
            });
    }
    
    // 加载客户项目
    function loadCustomerProjects() {
        const customerId = customerSelect.value;
        if (!customerId) {
            projectSelect.innerHTML = '<option value="0">请先选择客户</option>';
            return;
        }
        
        fetch(`/followup/api/customers/${customerId}/projects`)
            .then(response => response.json())
            .then(data => {
                projectSelect.innerHTML = '<option value="0">请选择项目</option>';
                
                if (data.user_projects && data.user_projects.length > 0) {
                    data.user_projects.forEach(project => {
                        const option = document.createElement('option');
                        option.value = project.id;
                        option.textContent = `${project.name} (${project.status})`;
                        projectSelect.appendChild(option);
                    });
                } else if (data.all_projects && data.all_projects.length > 0) {
                    // 如果用户没有在跟项目，但客户有项目，显示所有项目
                    data.all_projects.forEach(project => {
                        const option = document.createElement('option');
                        option.value = project.id;
                        option.textContent = `${project.name} (${project.status})`;
                        projectSelect.appendChild(option);
                    });
                } else {
                    projectSelect.innerHTML = '<option value="0">该客户暂无项目</option>';
                }
            })
            .catch(error => {
                console.error('Error loading projects:', error);
                projectSelect.innerHTML = '<option value="0">加载项目失败</option>';
            });
    }
    
    // 更新客户预览
    function updateCustomerPreview() {
        const customerId = customerSelect.value;
        if (!customerId) {
            customerPreview.innerHTML = '<p class="text-gray-500">请选择客户</p>';
            return;
        }
        
        fetch(`/followup/api/customers/${customerId}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    customerPreview.innerHTML = `<p class="text-red-600">${data.error}</p>`;
                    return;
                }
                
                let html = `
                    <div class="p-4">
                        <h6 class="text-sm font-medium text-gray-900 mb-3">${data.name}</h6>
                        <div class="space-y-2">
                            <p class="text-sm text-gray-700">
                                <strong>行业:</strong> ${data.industry || '未设置'}
                            </p>
                            <p class="text-sm text-gray-700">
                                <strong>来源:</strong> ${data.source || '未设置'}
                            </p>
                            <p class="text-sm text-gray-700">
                                <strong>状态:</strong> ${data.status || '未设置'}
                            </p>
                        </div>
                `;
                
                if (data.description) {
                    html += `<p class="text-sm text-gray-600 mt-3">${data.description}</p>`;
                }
                
                html += '</div>';
                customerPreview.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading customer:', error);
                customerPreview.innerHTML = '<p class="text-red-600">加载客户信息失败</p>';
            });
    }
    
    // 更新联系人预览
    function updateContactPreview() {
        const contactId = contactSelect.value;
        if (!contactId) {
            contactPreview.style.display = 'none';
            return;
        }
        
        fetch(`/api/contacts/${contactId}`)
            .then(response => response.json())
            .then(data => {
                document.getElementById('preview-contact-name').textContent = data.name || '';
                document.getElementById('preview-contact-title').textContent = data.title || '';
                document.getElementById('preview-contact-phone').textContent = data.phone || '';
                document.getElementById('preview-contact-email').textContent = data.email || '';
                
                contactPreview.style.display = 'block';
            })
            .catch(error => {
                console.error('Error loading contact:', error);
                contactPreview.style.display = 'none';
            });
    }
    
    // 加载历史跟进记录
    function loadFollowupHistory() {
        const customerId = customerSelect.value;
        if (!customerId) {
            return;
        }
        
        fetch(`/followup/api/customers/${customerId}/followups`)
            .then(response => response.json())
            .then(data => {
                const historyContainer = document.getElementById('followup-history');
                historyContainer.innerHTML = '';
                
                if (data.followups && data.followups.length > 0) {
                    data.followups.forEach(followup => {
                        const item = document.createElement('div');
                        item.className = 'border-b border-gray-200 pb-4 mb-4 last:border-b-0';
                        
                        const date = new Date(followup.followup_time);
                        const formattedDate = date.toLocaleDateString('zh-CN');
                        
                        item.innerHTML = `
                            <div class="flex justify-between items-start mb-2">
                                <h6 class="text-sm font-medium text-gray-900">${followup.method || '未设置'}</h6>
                                <span class="text-xs text-gray-500">${formattedDate}</span>
                            </div>
                            <p class="text-sm text-gray-700 mb-2">${followup.content || '无内容'}</p>
                            <p class="text-xs text-gray-600">跟进人: ${followup.user_name || '未知'}</p>
                        `;
                        
                        historyContainer.appendChild(item);
                    });
                } else {
                    historyContainer.innerHTML = '<div class="text-gray-500 py-4">暂无跟进记录</div>';
                }
            })
            .catch(error => {
                console.error('Error loading followup history:', error);
                document.getElementById('followup-history').innerHTML = '<div class="text-red-600 py-4">加载跟进记录失败</div>';
            });
    }
    
    // 编辑模式下加载数据
    {% if followup %}
        // 设置客户选择
        customerSelect.value = {{ followup.customer_id }};
        // 加载客户联系人和项目
        loadCustomerContacts();
        loadCustomerProjects();
        // 设置项目选择
        setTimeout(() => {
            projectSelect.value = {{ followup.project_id or 0 }};
        }, 500);
        // 设置联系人选择
        setTimeout(() => {
            {% if followup.contact_ids %}
                const contactIds = {{ followup.contact_ids|tojson }};
                contactIds.forEach(id => {
                    const checkbox = document.getElementById(`contact_${id}`);
                    if (checkbox) {
                        checkbox.checked = true;
                    }
                });
            {% endif %}
        }, 500);
        // 加载历史记录
        loadFollowupHistory();
        // 更新预览
        updateCustomerPreview();
        
        // 设置解决方案配合
        {% if followup.solution_support %}
            document.getElementById('solution_support').checked = true;
            updateSolutionSupportVisibility();
            {% if followup.solution_support_user_id %}
                setTimeout(() => {
                    document.getElementById('solution_support_user_id').value = {{ followup.solution_support_user_id }};
                }, 500);
            {% endif %}
        {% endif %}
    {% endif %}
});
</script>
{% endblock %}